/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.swirrel.installer;

import java.awt.Button;
import org.swirrel.listener.SwirrelActionListener;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractButton;
import org.swirrel.annotation.ActionPerformed;
import org.swirrel.listener.SwirrelAction;
import org.swirrel.Swirrel;
import javax.swing.Action;
import org.swirrel.util.MethodCall;

/**
 *
 * @author Gronau
 */
public class ActionListenerInstaller extends AbstractListenerInstaller implements SwirrelListenerInstaller {

    public ActionListenerInstaller() {
        super(Arrays.<Class<? extends Annotation>>asList(ActionPerformed.class),
                Arrays.<Class<?>>asList(AbstractButton.class, Button.class));
    }

    public boolean isListenerAlreadySet(Object obj) {
        ActionListener[] actionListeners = (obj instanceof AbstractButton)
                ? ((AbstractButton) obj).getActionListeners()
                : ((Button) obj).getActionListeners();
        for (ActionListener al : actionListeners) {
            if (al instanceof SwirrelActionListener) {
                return true;
            }
        }
        if(obj instanceof AbstractButton && ((AbstractButton) obj).getAction() instanceof SwirrelAction) {
          return true;
        }
        return false;
    }

    public void registerListener(Field field, Component comp, List<MethodCall> methodCalls) throws IllegalAccessException {
        MethodCall methodCall = methodCalls.get(0);
        Object obj = field.get(comp);
        Action action = Swirrel.getAction(methodCall.isThreaded(),
                                          methodCall.getComponent(), methodCall.getMethod());
        if (action != null && obj instanceof AbstractButton) {
          ((AbstractButton) obj).setAction(action);
          ((AbstractButton) obj).repaint();
        } else {
          ActionListener al = new SwirrelActionListener(methodCall);
          if (obj instanceof AbstractButton) {
            ( (AbstractButton) obj).addActionListener(al);
          }
          else {
            ( (Button) obj).addActionListener(al);
          }
        }
    }
}
